﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Reflection;

namespace mBlog.Core
{
    public class mBlogModelBinder<T> : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var instance = Activator.CreateInstance(typeof(T));

            var properties = bindingContext.ModelType.GetProperties();
            foreach (var prop in properties)
            {
                if (bindingContext.PropertyFilter(prop.Name))
                {

                    var result = bindingContext.ValueProvider
                        .GetValue(prop.Name);

                    if (result != null)
                    {
                        var value = result.ConvertTo(prop.PropertyType);

                        prop.SetValue(instance, value, null);
                    }
                }
            }

            return instance;
        }
    }
}
